<template>
  <view class="page-container">
    <!-- 顶部搜索区域 -->
    <view class="search-header">
      <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
      <view class="search-bar">
        <view class="back-btn" @click="goBack">
          <uni-icons type="back" size="20" color="#333"></uni-icons>
        </view>
        <view class="search-input">
          <uni-icons type="search" size="16" color="#e84d1c"></uni-icons>
          <input 
            type="text" 
            v-model="keyword" 
            placeholder="请输入商品名称/规格搜索" 
            placeholder-class="placeholder"
            confirm-type="search"
            focus
            @confirm="handleSearch"
          >
          <view class="clear-btn" v-if="keyword" @click="clearSearch">
            <uni-icons type="clear" size="14" color="#999"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 搜索结果区域 -->
    <scroll-view 
      class="result-container"
      :style="{ top: contentTop + 'px' }"
      scroll-y
      @scrolltolower="loadMore"
      :show-scrollbar="false"
      :enhanced="true"
      :bounces="true"
      v-if="loaded"
    >
      <!-- 结果统计 -->
      <view class="result-stats" v-if="loaded">
        <text>共找到 {{ total }} 个相关订单</text>
      </view>

      <!-- 订单列表 -->
      <view class="order-list" v-if="orderList.length > 0">
        <view 
          class="order-item"
          v-for="item in orderList"
          :key="item.id"
          @click="navigateToDetail(item)"
        >
          <!-- 订单头部 -->
          <view class="order-header">
            <text class="order-time">下单时间：{{ item.createTime }}</text>
            <text :class="['order-status', getStatusClass(item)]">{{ getStatusText(item) }}</text>
          </view>

          <!-- 商品信息 -->
          <view 
            class="goods-item"
            v-for="detail in item.details"
            :key="detail.id"
          >
            <album 
              width="150rpx" 
              style="width: fit-content" 
              height="150rpx" 
              :showExtraImages="false"
              :images="detail.images"
              :maxCount="1" 
              :previewEnabled="false"
            />
            <view class="goods-info">
              <view class="goods-name-row">
                <text class="goods-name">{{ detail.productVo?.productName }}</text>
                <text class="goods-price">¥{{ detail.unitPrice }}</text>
              </view>
              <view class="goods-spec-row">
                <text class="goods-spec">{{ detail.specificationVo?.specName }}</text>
                <text class="goods-quantity">x{{ detail.quantity }}</text>
              </view>
              <!-- 退款状态 -->
              <view class="refund-status" v-if="detail.refundVo">
                <text :class="['refund-tag', getRefundClass(detail.refundVo)]">
                  {{ getRefundText(detail.refundVo) }}
                </text>
              </view>
            </view>
          </view>

          <!-- 订单底部 -->
          <view class="order-footer">
            <view class="total-info">
              共{{ item.totalQuantity }}件商品
              <text class="total-price">
                {{ item.orderStatus === 0 ? '需付款' : '实付款' }}
                <text class="price">¥{{ item.totalAmount }}</text>
              </text>
            </view>
            <!-- 订单操作按钮 -->
            <view class="action-buttons" v-if="[0,2].includes(item.orderStatus) && !item.closed">
              <button 
                class="btn btn-default" 
                v-if="item.orderStatus === 0"
                @click.stop="cancelOrder(item)"
              >取消订单</button>
              <button 
                class="btn btn-primary" 
                v-if="item.orderStatus === 0 && item.remainSeconds > 0"
                @click.stop="pay(item)"
              >
                立即下单{{ formatSeconds(item.remainSeconds) }}
              </button>
              <button 
                class="btn btn-primary" 
                v-if="item.orderStatus === 2"
                @click.stop="receipt(item)"
              >确认收货</button>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-else-if="loaded">
        <image src="/static/images/empty-search.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">未找到相关订单</text>
      </view>

      <!-- 加载更多 -->
      <uni-load-more :status="loadingType"></uni-load-more>
    </scroll-view>

    <!-- 加载状态显示 -->
    <view class="loading-container" v-else>
      <view class="loading-spinner">
        <view class="loading-bounce"></view>
      </view>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script>
import { listSellOrder } from "@/api/sell/sellOrder";
import { cancelOrder, handleReceipt } from "@/api/sell/sellOrderDetail";
import { formatSeconds } from '@/utils/ruoyi';

export default {
  data() {
    return {
      statusBarHeight: 0,
      contentTop: 0,
      keyword: '',
      orderList: [],
      total: 0,
      loaded: false,
      loadingType: 'more',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      }
    }
  },

  created() {
    const systemInfo = uni.getSystemInfoSync();
    this.statusBarHeight = systemInfo.statusBarHeight;
    this.contentTop = this.statusBarHeight + 44; // 状态栏 + 搜索栏高度
  },

  onLoad(options) {
    if (options.keyword) {
      this.keyword = options.keyword;
      this.handleSearch();
    }
  },

  methods: {
    formatSeconds,
    
    // 搜索处理
    handleSearch() {
      if (!this.keyword.trim()) {
        return;
      }
      this.queryParams.pageNum = 1;
      this.queryParams.keyword = this.keyword;
      this.orderList = [];
      this.loadingType = 'loading';
      this.searchOrders();
    },

    // 加载更多
    loadMore() {
      if (this.loadingType === 'nomore' || this.loadingType === 'loading') {
        return;
      }
      this.queryParams.pageNum += 1;
      this.searchOrders();
    },

    // 搜索订单
    async searchOrders() {
      try {
        const res = await listSellOrder(this.queryParams);
        const { rows, total } = res;
        
        this.orderList = this.queryParams.pageNum === 1 
          ? rows 
          : [...this.orderList, ...rows];
        
        this.total = total;
        this.loaded = true;
        
        // 处理加载状态
        if (this.orderList.length >= total) {
          this.loadingType = 'nomore';
        } else {
          this.loadingType = 'more';
        }

        // 处理倒计时
        rows.forEach(order => {
          if (order.remainSeconds) {
            order.timer = setInterval(() => {
              order.remainSeconds--;
              if (order.remainSeconds <= 0) {
                clearInterval(order.timer);
                order.timer = null;
                this.handleSearch();
              }
            }, 1000);
          }
        });
      } catch (error) {
        this.loadingType = 'more';
        this.$modal.msgError('加载失败，请重试');
      }
    },

    // 清除搜索
    clearSearch() {
      this.keyword = '';
      this.handleSearch();
    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 跳转到订单详情
    navigateToDetail(item) {
      uni.navigateTo({
        url: `/pages/sellment/order/detail?orderDetailId=${item.id}`
      });
    },

    // 取消订单
    cancelOrder(item) {
      this.$confirmDialog.confirm('确定取消订单？').then(() => {
        this.$modal.loading('请稍后');
        return cancelOrder(item.id);
      }).then(() => {
        this.$modal.closeLoading();
        this.$modal.msgSuccess('取消成功');
        this.handleSearch();
      });
    },

    // 支付订单
    pay(item) {
      uni.navigateTo({
        url: `/pages/sellment/money/pay?orderId=${item.id}`
      });
    },

    // 确认收货
    receipt(item) {
      this.$confirmDialog.confirm('确认收货吗？').then(() => {
        return handleReceipt(item.id);
      }).then(() => {
        this.$modal.msgSuccess('收货成功');
        this.handleSearch();
      });
    },

    // 获取订单状态样式
    getStatusClass(item) {
      if (item.closed === 1) return 'status-closed';
      const statusMap = {
        0: 'status-pending',
        1: 'status-shipping',
        2: 'status-receiving',
        3: 'status-reviewing',
        4: 'status-completed'
      };
      return statusMap[item.orderStatus] || '';
    },

    // 获取订单状态文本
    getStatusText(item) {
      if (item.closed === 1) return '已关闭';
      const statusMap = {
        0: '待下单',
        1: '待发货',
        2: '待收货',
        3: '待评价',
        4: '已完成'
      };
      return statusMap[item.orderStatus] || '';
    },

    // 获取退款状态样式
    getRefundClass(refundVo) {
      if (refundVo.complete === 1) return 'refund-completed';
      const statusMap = {
        0: 'refund-pending',
        1: 'refund-approved',
        2: 'refund-rejected'
      };
      return statusMap[refundVo.status] || '';
    },

    // 获取退款状态文本
    getRefundText(refundVo) {
      const typeMap = {
        0: '换货',
        1: '退货退款',
        2: '仅退款'
      };
      const type = typeMap[refundVo.type] || '';
      
      if (refundVo.complete === 1) return `${type}售后完成`;
      
      const statusMap = {
        0: '申请中',
        1: '申请成功',
        2: '申请失败'
      };
      return `${type}${statusMap[refundVo.status]}`;
    }
  },

  // 组件销毁前清除定时器
  beforeDestroy() {
    this.orderList.forEach(order => {
      if (order.timer) {
        clearInterval(order.timer);
      }
    });
  }
}
</script>

<style lang="scss" scoped>
// 先定义 mixin
@mixin text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.page-container {
  min-height: 100vh;
  background: #f8f8f8;
}

.search-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: #fff;
}

.search-bar {
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 12px;
  
  .back-btn {
    padding: 6px 12px;
    margin-right: 8px;
  }
  
  .search-input {
    flex: 1;
    height: 32px;
    background: #f5f5f5;
    border-radius: 16px;
    display: flex;
    align-items: center;
    padding: 0 12px;
    
    .uni-icons {
      margin-right: 6px;
    }
    
    input {
      flex: 1;
      height: 100%;
      font-size: 14px;
      color: #333;
    }
    
    .clear-btn {
      padding: 6px;
      margin-left: 4px;
      
      &:active {
        opacity: 0.7;
      }
    }
  }
}

.result-container {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #f8f8f8;
  /* #ifdef H5 */
  top: calc(44px + 12px);
  /* #endif */
  /* #ifdef APP-PLUS */
  top: calc(var(--status-bar-height) + 44px + 12px);
  /* #endif */
  padding: 0 0 env(safe-area-inset-bottom);
  -webkit-overflow-scrolling: touch;
}

.result-stats {
  padding: 12px 16px;
  font-size: 13px;
  color: #999;
}

.order-list {
  padding: 20rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
}

.order-item {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
  
  &:last-child {
    margin-bottom: 0;
  }
}

.order-header {
  display: flex;
  align-items: center;
  height: 80rpx;
  font-size: 26rpx;
  color: #333;
  position: relative;
  border-bottom: 1rpx solid #f5f5f5;
  margin-bottom: 10rpx;
  padding: 0;
  
  .order-time {
    flex: 1;
    color: #666;
  }
  
  .order-status {
    font-size: 26rpx;
    font-weight: 500;
    padding: 4rpx 12rpx;
    border-radius: 4rpx;
    
    &.status-pending {
      color: #ff9900;
      background: rgba(255, 153, 0, 0.1);
    }
    
    &.status-shipping {
      color: #e84d1c;
      background: rgba(232, 77, 28, 0.1);
    }
    
    &.status-receiving {
      color: #2b85e4;
      background: rgba(43, 133, 228, 0.1);
    }
    
    &.status-reviewing {
      color: #19be6b;
      background: rgba(25, 190, 107, 0.1);
    }
    
    &.status-completed {
      color: #52c41a;
      background: rgba(82, 196, 26, 0.1);
    }
    
    &.status-closed {
      color: #999;
      background: rgba(153, 153, 153, 0.1);
    }
  }
}

.goods-item {
  display: flex;
  padding: 20rpx 0;
  position: relative;
  
  &:active {
    background: #fafafa;
  }

  .goods-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0 0 0 20rpx;
    overflow: hidden;
  }
  
  .goods-name-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10rpx;
  }
  
  .goods-name {
    font-size: 28rpx;
    color: #333;
    line-height: 1.4;
    @include text-ellipsis;
  }
  
  .goods-price {
    font-size: 30rpx;
    color: #333;
    font-weight: 600;

    &:before {
      content: '¥';
      font-size: 24rpx;
      margin: 0 2rpx 0 0;
      font-weight: normal;
    }
  }
  
  .goods-spec-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .goods-spec {
    font-size: 24rpx;
    color: #999;
    line-height: 1.4;
    @include text-ellipsis;
  }
  
  .goods-quantity {
    font-size: 24rpx;
    color: #999;
  }
}

.refund-status {
  margin-top: 10rpx;
  display: flex;
  justify-content: flex-end;
  
  .refund-tag {
    font-size: 22rpx;
    padding: 4rpx 12rpx;
    border-radius: 4rpx;
    
    &.refund-pending {
      color: #ff9900;
      background: rgba(255, 153, 0, 0.1);
    }
    
    &.refund-approved {
      color: #e84d1c;
      background: rgba(232, 77, 28, 0.1);
    }
    
    &.refund-rejected {
      color: #666;
      background: rgba(102, 102, 102, 0.1);
    }
    
    &.refund-completed {
      color: #333;
      background: rgba(51, 51, 51, 0.1);
    }
  }
}

.order-footer {
  padding: 20rpx 0;
  border-top: 1rpx solid #f5f5f5;
  margin-top: 10rpx;
  
  .total-info {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-size: 26rpx;
    color: #666;
    margin-bottom: 20rpx;
    
    .total-price {
      margin-left: 8rpx;
      
      .price {
        font-size: 32rpx;
        color: #e84d1c;
        font-weight: 600;
        margin-left: 4rpx;

        &:before {
          content: '¥';
          font-size: 24rpx;
          margin-right: 2rpx;
          font-weight: normal;
        }
      }
    }
  }
  
  .action-buttons {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .btn {
      min-width: 160rpx;
      height: 64rpx;
      margin-left: 20rpx;
      font-size: 26rpx;
      color: #666;
      background: #f8f8f8;
      border-radius: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s;
      border: none;
      padding: 0 30rpx;

      &:first-child {
        margin-left: 0;
      }

      &:after {
        border: none;
      }

      &:active {
        transform: scale(0.98);
      }

      &.btn-primary {
        background: linear-gradient(90deg, #e84d1c, #f06e44);
        color: #fff;
        font-weight: 500;
        box-shadow: 0 4rpx 16rpx rgba(232, 77, 28, 0.3);
        
        &:active {
          transform: scale(0.98);
          box-shadow: 0 2rpx 8rpx rgba(232, 77, 28, 0.2);
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  padding-bottom: env(safe-area-inset-bottom);
  
  .empty-image {
    width: 200px;
    height: 200px;
    margin-bottom: 16px;
  }
  
  .empty-text {
    font-size: 14px;
    color: #999;
  }
}

.placeholder {
  color: #999;
  font-size: 14px;
}

/* 加载动画样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 240rpx);
  animation: fadeIn 0.5s ease-out;
  
  .loading-spinner {
    width: 80rpx;
    height: 80rpx;
    position: relative;
    margin-bottom: 20rpx;
    
    .loading-bounce {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: rgba(232, 77, 28, 0.6);
      opacity: 0.6;
      position: absolute;
      top: 0;
      left: 0;
      animation: bounce 2s infinite ease-in-out;
      
      &:before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: rgba(232, 77, 28, 0.6);
        opacity: 0.6;
        animation: bounce 2s infinite ease-in-out;
        animation-delay: -1.0s;
      }
    }
  }
  
  .loading-text {
    color: #999;
    font-size: 28rpx;
  }
}

@keyframes bounce {
  0%, 100% { 
    transform: scale(0);
  }
  50% { 
    transform: scale(1.0);
  }
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { 
    opacity: 0;
    transform: translateY(20rpx);
  }
  to { 
    opacity: 1;
    transform: translateY(0);
  }
}
</style>